package com.example.springbootjavafx.view;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.springbootjavafx.domain.User;
import com.example.springbootjavafx.scopes.UserDetailScope;
import com.example.springbootjavafx.service.UserService;
import de.saxsys.mvvmfx.InjectScope;
import de.saxsys.mvvmfx.ScopeProvider;
import de.saxsys.mvvmfx.ViewModel;
import javafx.beans.property.*;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;



@Component
@Slf4j
@ScopeProvider(UserDetailScope.class)
public class ListViewModel implements ViewModel {

    private final ReadOnlyStringWrapper id = new ReadOnlyStringWrapper();
    private final ReadOnlyStringWrapper name = new ReadOnlyStringWrapper();
    private final ReadOnlyStringWrapper address = new ReadOnlyStringWrapper();

    private final ReadOnlyStringWrapper username = new ReadOnlyStringWrapper();


    public ObservableList<User> userList = FXCollections.observableArrayList();

    @InjectScope
    UserDetailScope userDetailScope;

    @Autowired
    private UserService userService;


    public void initialize() {

        //读取数据库数据
        userList.clear();
        this.userList.addAll(this.userService.list());

    }


    public ReadOnlyStringWrapper idLabelTextProperty() {
        return id;
    }
    public ReadOnlyStringWrapper nameLabelTextProperty() {
        return name;
    }
    public ReadOnlyStringWrapper addressLabelTextProperty() {
        return address;
    }

    public ReadOnlyStringWrapper usernameTextProperty() {
        return username;
    }


    public ObservableList<User> getUserList() {
        return userList;
    }


    public void deleteUser() {
        userService.removeById(id.get());
    }

    public void searchUser() {
        userList.clear();
//        log.info("--------------------------> username:{}", username.get());
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.like("name", username.get()==null?"":username.get());
        this.userList.addAll(this.userService.list(wrapper));
    }


}
